#!/bin/bash

if [ $# -eq 1 ] && [ "$1" != "traj" ]; then
  echo "Invalid command line option: $1 "
  exit
fi

# ncep, camseamip, none other
whichdata="camseamip"
breakblocks="monthly"
dorebuild=true
STARTYEAR=1980
ENDYEAR=2002

### Set directories
homedir=/glade/u/home/zarzycki
basedir=/glade/scratch/zarzycki/camsetracking

PATH=$PATH:/glade/u/home/zarzycki/tstorms/source/trajectory:/glade/u/home/zarzycki/tstorms/source/tstorms
export PATH

if [ "$1" != "traj" ]; then

  mkdir -p $basedir

  ### Build binary
  if $dorebuild ; then
    rm *.mod
    rm *.o
    rm *.exe
    ./compile_it tstorms_drive
  fi
  
  ###### --------------- LOOP
  
  for DATA_YEAR in $(eval echo {$STARTYEAR..$ENDYEAR})
  do
   for DATA_MONTH in 01 02 03 04 05 06 07 08 09 10 11 12
  # for DATA_MONTH in 05 06 07 08 09 10 11
  # for DATA_MONTH in 08 09 10
  # for DATA_MONTH in 01
    do
  
      #datadir=$basedir/$loopdir
      
      echo "Sedding"
      ## Sed into run_parallel.csh file
      sed -i "s?^DATA_YEAR.*?DATA_YEAR=${DATA_YEAR}?" run_parallel.sh
      sed -i "s?^DATA_MONTH.*?DATA_MONTH=${DATA_MONTH}?" run_parallel.sh    
      sed -i "s?^homedir.*?homedir=${homedir}?" run_parallel.sh
      sed -i "s?^basedir.*?basedir=${basedir}?" run_parallel.sh
      if [ $breakblocks == "yearly" ]; then
        sed -i "s?^loopdir.*?loopdir=${DATA_YEAR}?" run_parallel.sh
      elif [ $breakblocks == "monthly" ]
      then
        sed -i "s?^loopdir.*?loopdir=${DATA_YEAR}/${DATA_MONTH}?" run_parallel.sh
      else
        echo "Incorrect block breaking structure, exiting"
        exit
      fi
  
      echo "Subbing ${DATA_YEAR}/${DATA_MONTH}"
      
      bsub < run_parallel.sh
      
    done
    
  done

fi

###### --------------- END LOOP



if [ "$1" == "traj" ]; then
  echo "Catting"
  
  for DATA_YEAR in $(eval echo {$STARTYEAR..$ENDYEAR})
  do
    for DATA_MONTH in 01 02 03 04 05 06 07 08 09 10 11 12
    #for DATA_MONTH in 05 06 07 08 09 10 11    
    #for DATA_MONTH in 08 09 10    
    #for DATA_MONTH in 01
    do
  
    loopdir=${DATA_YEAR}/${DATA_MONTH}
    datadir=$basedir/$loopdir
    
    cd $basedir/${DATA_YEAR}
    
    ## Concatanate individual cyclone files into one yearly file
    ## stored at the base directory
    if [ ! -f $basedir/${DATA_YEAR}/cyclones_out ]; then
      echo "File not found!"
      cp $basedir/$loopdir/cyclones_out $basedir/${DATA_YEAR}/cyclones_out
    else
      cat $basedir/$loopdir/cyclones_out >> $basedir/${DATA_YEAR}/cyclones_out
    fi
  
    done

  cp cyclones_out cyclones
  
  if [ ! -e ./nml_trajectory  ]; then
  cat << eof > ./nml_trajectory
   &nml_trajectory
        wcrit =  17.0,
        rcrit =  400.0,
       nwcrit =  8,
      do_filt = .false.,
   /end
eof
  fi
  
  ~/tstorms/source/trajectory/trajectory.exe < ./nml_trajectory
  
  head -16 stats
  
  # delete copy of cyclones file
  rm -f cyclones

done

fi
